package role_api

import (
	"benkendSystem/database"
	"benkendSystem/models"
	"github.com/gin-gonic/gin"
	"net/http"
)

// Contains 判断元素是否在切片中
func Contains[T comparable](slice []T, elem T) bool {
	for _, v := range slice {
		if v == elem {
			return true
		}
	}
	return false
}

// AddRoleForUser 给人员添加角色
func AddRoleForUser(c *gin.Context) {
	in := new(AddRoleForUserRequest)
	err := c.ShouldBindJSON(in)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "参数错误",
		})
		return
	}
	var users []int64
	err = database.DB.Model(new(models.UserRole)).Where("role_id = ?", in.RoleId).Find(&users).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "系统错误",
		})
		return
	}
	var user_name []string
	for _, userId := range in.UserIds {
		if Contains(users, userId) {
			var username string
			err = database.DB.Model(new(models.User)).Where("id = ?", userId).Find(&username).Error
			if err != nil {
				c.JSON(http.StatusOK, gin.H{
					"code": 500,
					"msg":  "系统错误",
				})
				return
			}
			user_name = append(user_name, username)
			continue
		}
		err = database.DB.Model(new(models.UserRole)).Create(&models.UserRole{
			RoleId: in.RoleId,
			UserId: userId,
		}).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 500,
				"msg":  "系统错误",
			})
			return
		}
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "操作成功",
		"data": gin.H{
			"success": len(in.UserIds) - len(user_name),
			"failed":  len(user_name),
		},
	})

}
